package com.tencreat.framework.web.service;

import com.tencreat.common.constant.Constants;
import com.tencreat.common.core.domain.entity.SysRole;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.redis.RedisCache;
import com.tencreat.common.core.service.TokenService;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.exception.user.CaptchaException;
import com.tencreat.common.exception.user.CaptchaExpireException;
import com.tencreat.common.exception.user.UserPasswordNotMatchException;
import com.tencreat.common.utils.DictUtils;
import com.tencreat.common.utils.MessageUtils;
import com.tencreat.common.utils.spring.SpringUtils;
import com.tencreat.framework.manager.AsyncManager;
import com.tencreat.framework.manager.factory.AsyncFactory;
import com.tencreat.mapper.system.SysRoleMapper;
import com.tencreat.mapper.system.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import oshi.driver.mac.net.NetStat;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @Company: 深圳腾创互联科技有限公司
 * @link: https://tencreat.com/#/
 * @author tencreat
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
//     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password,  String uuid, Integer type, Integer store) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        String SUPER_CODE = DictUtils.getDictValue("code_config", "super_code");
        // 超级验证码是否有效 0-无效
        String status = DictUtils.getDictValue("code_config", "status");

//        // 超级验证码无效，必须校验验证码
//        if (status.equals("0") && !code.equalsIgnoreCase(captcha)) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//            throw new CaptchaException();
//        } else if (status.equals("1") && !code.equals(SUPER_CODE) && !code.equalsIgnoreCase(captcha)) {
//            // 超级验证码有效，并且超级验证码和验证码不对
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//            throw new CaptchaException();
//        }
        // 用户验证
        Authentication authentication = null;
        try {
            String username2 = username + ":" + store;
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username2, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 是否是供应商账号
        Integer countSupplier = sysUserRoleMapper.userRoleByRoleId(4L, loginUser.getUser().getUserId(), store);
        //是否是店铺账号
        Integer countStore = sysUserRoleMapper.userRoleByRoleId(24L, loginUser.getUser().getUserId(), store);
        if (type == 1 && countSupplier <= 0) {
            throw new CustomException("商城供应商账号有误");
        }
        if (type == 2 && countStore <= 0) {
            throw new CustomException("店铺账号信息有误");
        }
        if (type == 0 && countSupplier > 0 && countStore > 0) {
            throw new CustomException("管理员账号有误");
        }

        // 生成token
        return tokenService.createToken(loginUser);
    }

}

